package org.simplextensions.registry.phaselisteners;

import javassist.bytecode.annotation.Annotation;
import org.simplextensions.Utils;
import org.simplextensions.annotations.ExtensionStyle;
import org.simplextensions.registry.*;
import org.simplextensions.scanner.ClassScannerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExtensionScanPhaseListener implements ISimpleXtensionsClassScanner {

	private static final Logger log = LoggerFactory.getLogger(ExtensionScanPhaseListener.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.simplextensions.core.scanner.IScanPhaseListener#scanClass(java
	 * .lang.Class, javassist.bytecode.annotation.Annotation)
	 */
	public void scanClass(SimpleXtensionsBundle bundle, String className, Annotation a) {
		log.trace("scanning extension's class: " + className);

		String substring = className.substring(className.lastIndexOf(".") + 1);

		String smvId = ClassScannerHelper.getStringValue(a, "id", substring + Utils.getSequenceValue(substring));
		String smvPointId = ClassScannerHelper.getStringValue(a, "pointId", null);
		String smvFM = ClassScannerHelper.getStringValue(a, "factoryMethod");
		ExtensionStyle emvStyle = (ExtensionStyle) ClassScannerHelper.getEnumValue(a, "style");

		Extension extension = new Extension(bundle, className, smvId, emvStyle, smvFM);

		if (smvPointId == null)
			smvPointId = processExtension( extension);

		bundle.getExtensionRegistry().addExtension(extension, smvPointId);
	}

	public String processExtension(Extension extension) {
		for (ExtensionPoint ep : extension.getExtensionRegistry().getExtensionPointsMD()) {
			for (Class<?> c : ep.getDefaultExtensionClasses())
				if (c.isAssignableFrom(extension.getClazz())) {
					log.trace("registering extension: " + extension.getId() + " with extension point: " + ep.getId());
					return ep.getId();
				}
		}
		return null;
	}

}